<?php
/**
 * Created by andrei
 * Date: 8/3/12
 * Time: 9:55 AM
 */

class Db_Cms_Skins extends Common {
	protected static $tableName = TAB_SKINS;
	protected static $dbFields = array(
		'id',
		'sk_project_identifier',
		'sk_key',
		'sk_name',
		'sk_is_default',
		'deleted'
	);
    /**
     * @var Db_Cms_Skins
     */
    public $objectArray;

	public $id;
	public $sk_project_identifier;
	public $sk_key;
	public $sk_name;
	public $sk_is_default;
	public $deleted;

	function __construct($value=NULL, $fieldName=NULL) {
		parent::__construct($value, $fieldName);
	}

	public static function getCurrentSkin() {
		$sql = "SELECT `sk`.`sk_key`, `sk`.`sk_name`, `sf`.`sf_file_name`, `sf`.`sf_file_type`, `sf`.`sf_special_content`, `sf`.`sf_media`, `sf`.`sf_is_static`
				FROM ?f AS `sk`
				LEFT JOIN ?f AS `sf` ON `sf`.`sf_skin_id` = `sk`.`id` AND `sf`.`deleted` = 0
				WHERE `sk`.`sk_project_identifier` = ? AND `sk`.`sk_is_default` = 1 AND `sk`.`deleted` = 0
				ORDER BY `sf`.`sf_file_type`, `sf`.`sf_position`;";
		$result = self::$DB->q($sql, self::$tableName, TAB_SKIN_FILES, PROJECT);
		if ($result->num_rows <= 0) {
			$sql = "SELECT `sk`.`sk_key`, `sk`.`sk_name`, `sf`.`sf_file_name`, `sf`.`sf_file_type`, `sf`.`sf_special_content`, `sf`.`sf_media`, `sf`.`sf_is_static`
					FROM ?f AS `sk`
					LEFT JOIN ?f AS `sf` ON `sf`.`sf_skin_id` = `sk`.`id` AND `sf`.`deleted` = 0
					WHERE `sk`.`sk_project_identifier` = ? AND `sk`.`sk_key` = ? AND `sk`.`deleted` = 0
					ORDER BY `sf`.`sf_position` ASC;";
			$result = self::$DB->q($sql, self::$tableName, TAB_SKIN_FILES, PROJECT, DEFAULT_SKIN_FOLDER);
		}
		$skinSettings = array();
		while ($data = $result->fetch_assoc()) {
			if (!isset($skinSettings['key'])) {
				$skinSettings['key'] = $data['sk_key'];
				$skinSettings['name'] = $data['sk_name'];
			}
			$skinSettings['files'][$data['sf_file_type']][] = array(
				'name' => $data['sf_file_name'],
				'special_content' => $data['sf_special_content'],
				'media' => $data['sf_media'],
				'static' => $data['sf_is_static']
			);
		}
		return $skinSettings;
	}

    public static function getAllSkins() {
        $skin = array();
        $sql = "SELECT * FROM ?f WHERE `deleted` = 0 ;";
        $result = self::$DB->q($sql, self::$tableName);
        while($data = $result->fetch_assoc()){
            $skin[$data['sk_project_identifier']][] = $data;
        }
        return $skin;
    }

    public static function removeDefaultSkin($projectIdentifier){
        $sql = "UPDATE ?f SET `sk_is_default` = 0 WHERE `sk_project_identifier` = ? AND `deleted` = 0";
        return self::$DB->q($sql, self::$tableName, $projectIdentifier);
    }

    public static function getSkinName($skinId){
       return self::$DB->selectCell("SELECT `sk_name` FROM ?f WHERE `id`= ?d AND `deleted` = 0;", self::$tableName, $skinId);
    }
}